import React, { Key, useEffect, useState } from 'react'

import styles from './index.module.less'

import { useNavigate } from 'react-router-dom'

import { SearchOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons'
import { Button, Form, Input, Table, PaginationProps, Card, message } from 'antd'
import type { ColumnsType } from 'antd/es/table'

import { getHosListRequestReturnItemType, getHosListRequestReturnRecordsType } from '@/api/hospitalSet/model/hospitalSetTypes'
import { getHosListRequest, deleteHosRequest, batchRemoveHospitalListRequest } from '@/api/hospitalSet'

import { fieldsValue } from './type'
import { clearScreenDown } from 'readline'

export default function HospitalSet() {

  const navigate = useNavigate()

  const [data, setData] = useState<getHosListRequestReturnRecordsType>([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(5)
  const [total, setTotal] = useState(0);
  const [isLoading, setIsLoading] = useState(true)

  // 表单实例
  const [form] = Form.useForm<fieldsValue>()


  const getHosList = async (current: number, pageSize: number) => {
    setIsLoading(true)
    // 获取 from 的值
    const { hosname, hoscode } = form.getFieldsValue()
    try {
      const result = await getHosListRequest({
        page: current,
        limit: pageSize,
        hosname,
        hoscode
      })
      const { records, total } = result
      setCurrent(current)
      setPageSize(pageSize)
      setTotal(total)
      setData(records)
      setIsLoading(false)
    } catch (error) {
      console.log(error);
    }
  }
  // useEffect 第一个参数不能为一个回调函数，否之 return 卸载组件前执行的函数就变成异步了，无法触发
  useEffect(() => {
    getHosList(current, pageSize)
  }, [])  // 不要监听 current, pageSize 变化之后在发送请求，这样的话会导致页面渲染完成后，新数据才回来，而新的 current, pageSize 使用的还是原来的旧数据就会导致 antdesign 报错

  const columns: ColumnsType<getHosListRequestReturnItemType> = [
    {
      title: "序号",
      width: 70,
      align: "center" as "center",
      // 当没有 dataIndex 使用 render 函数渲染数据
      render: (_: any, __: getHosListRequestReturnItemType, index: number) => {
        return index + 1
      }
    },
    {
      title: "医院名称",
      dataIndex: "hosname",
    },
    {
      title: "医院编号",
      dataIndex: "hoscode",
    },
    {
      title: "api基础路径",
      dataIndex: "apiUrl",
    },
    {
      title: "签名",
      dataIndex: "signKey",
    },
    {
      title: "联系人姓名",
      dataIndex: "contactsName",
    },
    {
      title: "联系人手机",
      // 纯数据渲染直接dataIndex
      dataIndex: "contactsPhone",
    },
    {
      title: "操作",
      width: 120,
      fixed: "right" as "right",
      render(_: any, item: getHosListRequestReturnItemType) {
        const { id } = item
        return (
          <>
            <Button
              className={styles.mr}
              type="primary"
              icon={<EditOutlined />}
              onClick={() => {
                navigate(`/syt/hospital/updateHospital/${id}`)
              }}
            />
            <Button
              type="primary"
              danger
              icon={<DeleteOutlined />}
              onClick={async () => {
                await deleteHosRequest(id)
                message.success('删除成功')
                getHosList(current, pageSize)
              }}
            />
          </>
        )
      },
    }
  ]

  // 点击查询按钮，触发的回调函数
  const onFinish = () => {
    getHosList(current, pageSize)
  };

  // 重置表单
  const reset = () => {
    // 清空表单内容
    form.resetFields()
    // 重新获取数据展示
    getHosList(current, pageSize)
  }

  // 添加
  const addHospital = () => {
    navigate('/syt/hospital/addHospital')
  }

  const [selectedHospitalIds, setSelectedHospitalIds] = useState<Key[]>([])

  const rowSelection = {
    onChange: (selectedRowKeys: Key[]) => {
      setSelectedHospitalIds(selectedRowKeys)
    }
  }

  const batchRemoveHosHandler = async () => {
    await batchRemoveHospitalListRequest(selectedHospitalIds)
    setSelectedHospitalIds([])
    message.success('删除成功')
    getHosList(current, pageSize)
  }

  const onShowSizeChange: PaginationProps['onShowSizeChange'] = (current, pageSize) => {
    getHosList(current, pageSize)
  }
  const onChange: PaginationProps['onChange'] = (current, pageSize) => {
    getHosList(current, pageSize)
  }
  return (
    <Card className={styles.outer}>
      <Form form={form} onFinish={onFinish} name="horizontal_login" layout="inline">
        <Form.Item
          name="hosname"
        >
          <Input placeholder="医院名称" />
        </Form.Item>
        <Form.Item
          name="hoscode"
        >
          <Input placeholder="医院编号" />
        </Form.Item>
        <Form.Item>
          <Button
            className={styles.mr}
            type="primary"
            htmlType="submit"
            icon={<SearchOutlined />}

          >
            查询
          </Button>
          <Button
            type="default"
            onClick={reset}
          >
            重置
          </Button>
        </Form.Item>
      </Form>
      <div className={styles.mt}>
        <Button className={styles.mr} type="primary" onClick={addHospital} >添加</Button>
        <Button type="primary" danger disabled={!selectedHospitalIds.length} onClick={batchRemoveHosHandler} >批量删除</Button>
      </div>
      <Table
        className={styles.mr}
        columns={columns}
        dataSource={data}
        rowKey='id'
        rowSelection={{
          type: 'checkbox',
          ...rowSelection
        }}
        bordered
        scroll={{
          x: 1500,
          y: 340
        }}
        pagination={{
          current,
          pageSize,
          total,
          onChange,
          showSizeChanger: true,
          onShowSizeChange,
          pageSizeOptions: [5, 10, 20, 40],
          showTotal: (total) => `总共 ${total} 条`
        }}
        loading={isLoading}
      />
    </Card>
  )
}
